package com.edais.mina;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.ReadFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import com.edais.mina.codec.DefaultCodec;
import com.edais.util.CommonUtil;

public class TcpMinaClient {
	private static Logger logger = Logger.getLogger(TcpMinaClient.class);

	private static String coreIp = "";
	private static String corePort = "";
	private static NioSocketConnector connector = new NioSocketConnector();
	private static final long CONNECT_TIMEOUT = 5 * 1000L; // 30 seconds
	private static final int IDLE_TIME = 2 * 60; // 2 * 60 seconds

	static {
		try {
			Properties props = PropertiesLoaderUtils.loadAllProperties("coreIP.properties");
			coreIp = props.getProperty("core_ip");
			corePort = props.getProperty("core_port");
			logger.info("Mina读取核心配置-" + coreIp + ":" + corePort);
		} catch (IOException e) {
			logger.error("读取核心配置失败", e);
		}
		DefaultIoFilterChainBuilder chain = connector.getFilterChain();
		chain.addLast("codec", (new DefaultCodec()).getCodecFilter());
		connector.setHandler(new ClientMinaServerHandler());
		connector.setConnectTimeoutMillis(CONNECT_TIMEOUT);
		connector.getSessionConfig().setBothIdleTime(IDLE_TIME);
	}

	public String sendMessage(String msg) {
		String reslult = "";
		IoSession session = null;
		try {
			ConnectFuture future = connector.connect(new InetSocketAddress(coreIp, Integer.valueOf(corePort)));
			future.awaitUninterruptibly();
			session = future.getSession();
			msg = CommonUtil.countRtnByte(msg, 8);
			session.write(msg);
			session.getConfig().setUseReadOperation(true);
			ReadFuture readFuture = session.read();
			readFuture.awaitUninterruptibly(IDLE_TIME, TimeUnit.SECONDS);
			reslult = readFuture.getMessage().toString();
		} catch (Exception e) {
			if(session != null) {
				logger.error("Mina 读写异常 sessionid:" + session.getId() + "，发送的内容为" + msg, e);
				throw new RuntimeException("Mina 读写异常 sessionid:" + session.getId(), e);
			} else {
				throw new RuntimeException("Mina 建立连接异常", e);
			}
		} finally {
			try {
				if (session != null && !session.isClosing()) {
					session.close(true);
				}
			} catch (Exception e) {
				logger.error("Mina 关闭session异常", e);
			}
		}
		return reslult;
	}

	public static void main(String[] args) throws InterruptedException {
		StringBuilder sb = new StringBuilder("");
		for (int i = 0; i < 1; i++) {
			sb.append("a");
		}
		for(int j = 0; j < 10; j++) {
			
			Map<String, Object> coreMap = new HashMap<String, Object>();
			coreMap.put("testStr", sb.toString());
			coreMap.put("testStrLength", sb.length());
			try {
				String res = CommonUtil.getCoreValue(CommonUtil.constructJsonStr("E999999", null, coreMap));
				logger.info("接收到的数据" + res);
			} catch (Exception e) {
				logger.error("Mina测试异常", e);
			}
		}
		connector.dispose();
	}
}